package com.rong.tools.service.impl;

import com.rong.tools.entity.dto.ToolDto;
import com.rong.tools.entity.pojo.Category;
import com.rong.tools.mappers.CategoryMapper;
import com.rong.tools.mappers.ToolMapper;
import com.rong.tools.entity.pojo.Tool;
import com.rong.tools.service.ToolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 周厚荣
 * @date 2025/4/20 23:22
 */
@Service
@Slf4j
public class ToolServiceImpl implements ToolService {
    @Autowired
    private ToolMapper toolMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public List<Tool> getAllTools() {
        return toolMapper.selectAllTools();
    }

    @Override
    public Tool getToolById(Integer id) {
        return toolMapper.selectToolById(id);
    }

    @Override
    public List<Tool> getToolByCategory(Integer categoryId) {
        return toolMapper.selectToolByCategory(categoryId);
    }

    @Override
    public boolean addTool(Tool tool) {
        return toolMapper.insertTool(tool) > 0;
    }

    @Override
    public boolean updateTool(Tool tool) {
        return toolMapper.updateTool(tool)>0;
    }

    @Override
    public boolean deleteTool(Integer id) {
        return toolMapper.deleteTool(id) > 0;
    }

    @Override
    public List<ToolDto> getToolWithCategoryName() {
        List<ToolDto> toolDtos = toolMapper.selectAllToolsWithCategoryName();
        return toolDtos;
    }

    @Override
    public boolean updateWithCategoryName(ToolDto toolDto) {
        Integer categoryId= categoryMapper.selectCategoryIdByName(toolDto.getCategoryName());
        if(categoryId!=null) {
            Tool tool = new Tool();
            BeanUtils.copyProperties(toolDto,tool);
            tool.setCategoryId(categoryId);
            toolMapper.updateTool(tool);
            return true;
        } else {
            throw new RuntimeException("分类不存在");
        }

    }

    @Override
    public boolean addWithCategoryName(ToolDto toolDto) {
        Integer categoryId= categoryMapper.selectCategoryIdByName(toolDto.getCategoryName());
        if(categoryId!=null) {
            Tool tool = new Tool();
            BeanUtils.copyProperties(toolDto,tool);
            tool.setCategoryId(categoryId);
            toolMapper.insertTool(tool);
            return  true;
        } else {
            throw new RuntimeException("分类不存在");
        }
    }

    @Override
    public List<Tool> search(String keyword) {
        return toolMapper.search(keyword);
    }
}
